package com.xfapp.demos.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xfapp.demos.common.Result;
import com.xfapp.demos.entity.Question;
import com.xfapp.demos.entity.UserAnswer;
import com.xfapp.demos.entity.WrongDataType;
import com.xfapp.demos.service.IUserAnswerService;
import com.xfapp.demos.service.IQuestionService;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 存储用户答题记录的表 前端控制器
 * </p>
 *
 * @author jinYi
 * @since 2025-06-06
 */
@RestController
@RequestMapping("/userAnswer")
public class UserAnswerController {

    @Resource
    private IUserAnswerService userAnswerService;

    @Resource
    private IQuestionService questionService;
    //未启用的保存方法
    @PostMapping("/save")
    public Result save(UserAnswer userAnswer) {
        boolean result = userAnswerService.save(userAnswer);
        if (result) {
            return Result.success();
        } else {
            return Result.error("-1", "保存失败");
        }
    }
    /**
     * 启用
     * 批量保存用户答题记录
     * @param userAnswerList
     * @return
     */
    @PostMapping("/addAll")
    public Result addAll( @RequestBody  List<UserAnswer> userAnswerList) {
        List<UserAnswer> validList = userAnswerList.stream()
                .filter(ua -> ua != null && ua.getUserId() != null && ua.getQuestionId() != null)
                .collect(Collectors.toList());
        if (validList.isEmpty()) {
            return Result.error("-1", "没有有效的答题记录");
        }
        boolean result = userAnswerService.saveOrUpdate(userAnswerList);
        if (result) {
            return Result.success();
        } else {
            return Result.error("-1", "保存失败");
        }
    }

    /**
     * 获取用户错题数据
     * */
    @GetMapping("/wrong/data/{userId}")
    public Result getWrongData(@PathVariable Integer userId){
        QueryWrapper<UserAnswer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).eq("correct",0);
        List<UserAnswer> list = userAnswerService.list(queryWrapper);

        if(list.isEmpty() && list.size() == 0){
            return Result.error("-1","没有错题");
        }
        //将list集合中的question_id过滤出来，用于到题目表中查询对应的题目
        List<Long> questionIds = list.stream().map(UserAnswer::getQuestionId).toList();
        QueryWrapper<Question> questionQueryWrapper = new QueryWrapper();
        QueryWrapper<Question> condition = questionQueryWrapper.eq("del_flag", 0).in("id", questionIds);
        List<Question> questionsList = questionService.list(condition);
        if(questionsList.isEmpty() && questionsList.size() == 0){
            return Result.error("-1","没有错题");
        }
        // 提取最后回答时间
        Map<Long, String> lastAnswerTimeMap = new HashMap<>();
        for (UserAnswer answer : list) {
            Question question = questionsList.stream()
                .filter(q -> q.getId().equals(answer.getQuestionId()))
                .findFirst()
                .orElse(null);
            if (question != null) {
                lastAnswerTimeMap.put(question.getId(), answer.getUpdateTime().toString());
            }
        }
        // 构建返回数据
        List<Map<String, Object>> formattedList = new ArrayList<>();
        for (Question question : questionsList) {
            Map<String, Object> record = new HashMap<>();
            record.put("id", question.getId());
            record.put("question", question.getQuestionText());
            record.put("lastAnswerTime", lastAnswerTimeMap.getOrDefault(question.getId(), ""));
            formattedList.add(record);
        }
        Map<String, Object> response = new HashMap<>();
        response.put("total", formattedList.size());
        response.put("list", formattedList);
        return Result.success(response);
    }

    /**
     * 获取用户错题数据详情
     * */
    @GetMapping("/findIndexData/{userId}")
    public Result getWrongDataDetail(@PathVariable Long userId) {
        // 查询用户所有答题记录
        QueryWrapper<UserAnswer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<UserAnswer> allAnswers = userAnswerService.list(queryWrapper);

        if (allAnswers == null || allAnswers.isEmpty()) {
            return Result.error("-1", "没有答题记录");
        }

        // 统计总答题数量
        int totalQuantity = allAnswers.size();

        // 筛选出错题
        List<UserAnswer> mistakes = allAnswers.stream()
                .filter(answer -> answer.getCorrect() == 0)
                .collect(Collectors.toList());
        int mistakesQuantity = mistakes.size();

        // 获取错题ID集合
        List<Long> mistakeQuestionIds = mistakes.stream()
                .map(UserAnswer::getQuestionId)
                .toList();

        // 查询题目信息
        List<Question> questions = questionService.list(
                new QueryWrapper<Question>().eq("del_flag", 0).in("id", mistakeQuestionIds)
        );

        if (questions == null || questions.isEmpty()) {
            return Result.error("-1", "没有错题数据");
        }

        // 按类型分类
        List<Question> listByRadios = questions.stream().filter(q -> q.getType() == 1).toList();
        List<Question> listByMultiples = questions.stream().filter(q -> q.getType() == 2).toList();
        List<Question> listByJudges = questions.stream().filter(q -> q.getType() == 3).toList();

        // 构建返回对象
        Map<String, Object> response = new HashMap<>();
        response.put("totalQuantity", totalQuantity);
        response.put("mistakesQuantity", mistakesQuantity);
        response.put("listByAll", questions);
        response.put("listByRadios", listByRadios);
        response.put("listByMultiples", listByMultiples);
        response.put("listByJudges", listByJudges);

        return Result.success(response);
    }

    /**
     * 真的删
     * @param
     * @return
     */
    @DeleteMapping("/deleteWrong/{questionId}/{userId}")
    public Result delete(@PathVariable Integer questionId,@PathVariable Integer userId)
    {
        System.out.println("questionid" + questionId + "useriD" + userId);
        QueryWrapper<UserAnswer> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId).eq("question_id",questionId);
        boolean result = userAnswerService.remove(queryWrapper);
        if (result) {
            return Result.success();
        } else {
            return Result.error("-1", "删除失败");
        }
    }
}
